package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.FileSubufferUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.BillReviewMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.BillOwnerMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.HousingOwadvanceMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.TemporaryMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 功能描述:
 * 业主提前收房
 *
 * @Auther: zhlu
 * @Date: 2019/1/12 15:45
 * @Description:
 */
@Service
public class HousingOwadvanceService {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(HousingOwadvanceService.class);

    @Autowired
    HousingOwadvanceMapper housingOwadvanceMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    TemporaryMapper temporaryMapper;

    @Autowired
    BillReviewMapper billReviewMapper;

    String UUID = null;

    String BiId = null;

    String BiOutId = null;

    /**
     * 功能描述:
     * 获取业主提前收房列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/12 15:47
     */
    public List<Map<String, Object>> getHousingOwList(Map<String, Object> params) {
        List<Map<String, Object>> getHousingOwList = housingOwadvanceMapper.getHousingOwList(params);
        return getHousingOwList;
    }

    /**
     * 功能描述:
     * 获取业主提前收房列表总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/12 15:49
     */
    public Integer getHousingOwListCout(Map<String, Object> params) {
        Integer getHousingOwListCout = housingOwadvanceMapper.getHousingOwListCout(params);
        return getHousingOwListCout;
    }

    /**
     * 功能描述:
     * 业主放弃提前收房
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/15 19:45
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdateHousingOwGiveUp(Map<String, Object> params) {
        boolean result = false;
        //所有修改处理
        Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
        commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
        commonUpdateParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        commonUpdateParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(commonUpdateParms);
        try {
            params.putAll(commonUpdateParms);
            housingOwadvanceMapper.UpdateHousingOwGiveUp(params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 发起违约单
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/16 14:48
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean AddHousingOwInfo(Map<String, Object> params) {
        boolean result = false;
        lock.lock();
        try {
            //查询业主违约单
            Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                put("uuid", "OwAdinfoId");
                put("database", Constants.DATA_SOURCE_GMIO);
                put("surface", "tcgmio_housing_owadvance_info");
            }});
            if (uuid != null) {
                int number = Integer.valueOf(uuid.get("uuid").toString());
                UUID = ComUtils.getLocalTrmSeqNum("yzwy", number);
            } else {
                UUID = ComUtils.getLocalTrmSeqNum("yzwy", 0);
            }

            //查询临时账单
            Map<String, Object> biId = utilsMapper.getUUID(new HashMap<String, Object>() {{
                put("uuid", "BiId");
                put("database", Constants.DATA_SOURCE_GMIO);
                put("surface", "tcgmio_tenant_bill");
            }});
            if (biId != null) {
                int number = Integer.valueOf(biId.get("uuid").toString());
                BiId = ComUtils.getLocalTrmSeqNum("zdsr", number);
            } else {
                BiId = ComUtils.getLocalTrmSeqNum("zdsr", 0);
            }

            //获取账单编号
            Map<String, Object> biOutId = utilsMapper.getUUID(new HashMap<String, Object>() {{
                put("uuid", "BiOutId");
                put("database", Constants.DATA_SOURCE_GMIO);
                put("surface", "tcgmio_bill_outlay");
            }});
            if (biOutId != null && (!biOutId.get("uuid").toString().equals(""))) {
                int number = Integer.valueOf(biOutId.get("uuid").toString());
                BiOutId = ComUtils.getLocalTrmSeqNum("zdzc" + 1, number);
            } else {
                BiOutId = ComUtils.getLocalTrmSeqNum("zdzc" + 1, 0);
            }

            //所有新增处理
            Map<String, Object> commonInsertParms = new HashMap<String, Object>();
            commonInsertParms.put("by", ContextUtils.getUserId());//操作人
            commonInsertParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonInsertParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(commonInsertParms);

            //所有修改处理
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
            commonUpdateParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);

            try {
                //违约单附件图片
                List<Map<String, Object>> AnnexList = (List<Map<String, Object>>) params.get("Annex");
                String Annex = FileSubufferUtils.ListTranStringUtils(AnnexList);
                params.put("Annex", Annex);
                params.putAll(commonInsertParms);
                params.put("OwAdinfoId", UUID);
                params.put("SysUserId", ContextUtils.getUserId());
                params.put("CreateTime", ConvertDateTime.getCurrentTime());
                //业主违约单主表
                housingOwadvanceMapper.AddHousingOwInfo(params);
                //业主提前收房
                housingOwadvanceMapper.UpdateHousingOwGiveUp(new HashMap<String, Object>() {{
                    put("OwAdId", params.get("OwAdId"));
                    put("Status", params.get("Status"));
                    put("AcceptId", params.get("SysUserId"));
                    putAll(commonUpdateParms);
                }});

                //根据业主合同编码修改唐巢支出所有账单未废弃
                params.put("Status", 3);
                billReviewMapper.updateRelationByBill(params);

                //收入-支出
             //   String payType= MapUtils.getString(params,"payType","0");
                //赔偿类型   1.业主赔偿唐巢金额    2.唐巢赔偿业主金额
                String payType= MapUtils.getString(params,"claimId","1");
                switch (payType){
                    //收入
       //             case "0":
                    case "1":
                        Map<String, Object> Temporary = new HashMap<String, Object>();
                        Temporary.put("BiId", BiId);
                        Temporary.put("CorId", params.get("CorId"));

                        Temporary.put("BiName", "业主违约单");
                        Temporary.put("BiType",11);
                        Temporary.put("Source",UUID);
                   //     Temporary.put("BiMoney",params.get("Payment"));
                        Temporary.put("BiMoney",params.get("billAmount"));
                        Temporary.put("BillExplain","因业主于" + params.get("StartTime") + "发起的违约单，需业主赔偿金额为￥" + params.get("Payment"));
                        Temporary.put("BiGenerated",ConvertDateTime.getCurrentTime());
                        Temporary.put("EndTime",params.get("PaymentTime"));
                                billReviewMapper.addBillPut(Temporary);
                        break;
                        //支出
            //        case "1":
                            case "2":
                        Map<String, Object> billOut = new HashMap<String, Object>();
                        billOut.put("BiOutId", BiOutId);
                        billOut.put("CorId", params.get("CorId"));
                        billOut.put("Period", 1);
                        billOut.put("BiOutName", "业主违约单");
                        //账单类型  1.业主   2.供应商  3.退租账单   4.公共事业费    5.账单撤回   6.业主违约退
                        billOut.put("BiOutType", 6);
                        billOut.put("Relation", UUID);
                      //  billOut.put("BiMoney", params.get("Payment"));
                        billOut.put("BiMoney", params.get("billAmount"));
                        billOut.put("BillExplain", "因业主于" + params.get("StartTime") + "发起的违约单，需赔偿业主金额为￥" + params.get("Payment"));
                        billOut.put("StartTime",ConvertDateTime.getCurrentTime());
                        billOut.put("EndTime",params.get("PaymentTime"));
                        billOut.put("LateDay",params.get("PaymentTime"));
                        billOut.put("StemType",1);
                        billOut.put("StemId",params.get("OwId"));
                        billOut.put("HouId",params.get("HouId"));
                        billOut.put("CreateType",1);
                        billOut.put("Create",params.get("SysUserId"));
                        billReviewMapper.addBillOut(billOut);
                        break;
                        default:
                                break;
                    }
                        result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } finally {
                lock.unlock();
            }

            return result;
        }
/**
 * 查询收费标准数据 根据收费标准的编号进行查询
 *
 * @param chaId
 * @return
 */
public JsonResult getChargesData(String chaId) {
        return JsonResult.success(housingOwadvanceMapper.getChargesData(chaId));
        }

        }
